<template>
  <div class="ai-chat-container">
  
    
    <div class="chat-messages card">
      <div v-for="(message, index) in messages" :key="index" 
           :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']">
        <div class="message-avatar">
          <el-avatar :icon="message.role === 'user' ? User : ChatDotRound" 
                    :size="40" 
                    :style="message.role === 'user' ? 'background-color: #2c82ff' : 'background-color: #31bf00'">
          </el-avatar>
        </div>
        <div class="message-content">
          <div class="message-text">{{ message.content }}</div>
          <div class="message-time">{{ message.time }}</div>
        </div>
      </div>
      
      <div v-if="loading" class="loading-message">
        <el-icon class="is-loading"><Loading /></el-icon> AI正在思考中...
      </div>
    </div>
    
    <div class="chat-input card">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="3"
        placeholder="请输入您的问题..."
        @keyup.enter.ctrl="sendMessage"
      />
      <div class="input-actions">
        <el-button type="primary" :disabled="!inputMessage.trim() || loading" @click="sendMessage">
          发送 <el-icon class="el-icon--right"><Position /></el-icon>
        </el-button>
        <div class="input-tip">提示: Ctrl + Enter 快速发送</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { User, ChatDotRound, Position, Loading } from '@element-plus/icons-vue';
import { sendQuestion, getChatHistory } from '@/api/ai';
import { ElMessage } from 'element-plus';

const inputMessage = ref('');
const loading = ref(false);
const messages = ref([
  {
    role: 'ai',
    content: '您好！我是AI助手，有什么可以帮助您的吗？',
    time: new Date().toLocaleTimeString()
  }
]);

// 获取历史对话
const fetchChatHistory = async () => {
  try {
    const res = await getChatHistory();
    if (res.data && res.data.length > 0) {
      // 将历史消息添加到当前消息列表
      messages.value = [
        ...res.data.map(item => ({
          role: item.role,
          content: item.content,
          time: new Date(item.timestamp).toLocaleTimeString()
        })),
        ...messages.value
      ];
    }
  } catch (error) {
    console.error('获取历史对话失败:', error);
  }
};

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) return;
  
  // 添加用户消息
  const userMessage = {
    role: 'user',
    content: inputMessage.value,
    time: new Date().toLocaleTimeString()
  };
  messages.value.push(userMessage);
  
  // 清空输入框
  const question = inputMessage.value;
  inputMessage.value = '';
  
  // 显示加载状态
  loading.value = true;

  // 测试模式开关（开发时使用，生产环境请设为false）
  const testMode = false; // 关闭测试模式，使用实际API
  
  if (testMode) {
    // 模拟延迟
    setTimeout(() => {
      // 模拟AI回复
      messages.value.push({
        role: 'ai',
        content: `您的问题是: "${question}"。这是一个测试回复，实际功能需要后端支持。`,
        time: new Date().toLocaleTimeString()
      });
      loading.value = false;
    }, 1000);
    return;
  }
  
  try {
    // 调用AI接口
    const res = await sendQuestion({ question });
    
    // 添加AI回复 - 修改这里以适应实际的后端响应格式
    messages.value.push({
      role: 'ai',
      // 根据实际后端返回的数据结构调整
      content: res.data ? (res.data.answer || res.data.content || JSON.stringify(res.data)) : '抱歉，无法获取回复',
      time: new Date().toLocaleTimeString()
    });
  } catch (error) {
    console.error('发送问题失败:', error);
    // 显示更详细的错误信息
    if (error.response) {
      // 服务器响应了，但状态码不在2xx范围
      ElMessage.error(`发送失败: ${error.response.status} - ${error.response.data.message || '未知错误'}`);
    } else if (error.request) {
      // 请求已发送但没有收到响应
      ElMessage.error('发送失败: 无法连接到服务器，请检查网络或后端服务是否启动');
    } else {
      // 请求设置时发生错误
      ElMessage.error(`发送失败: ${error.message}`);
    }
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchChatHistory();
});
</script>

<style scoped>
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 100px);
}

.chat-header {
  padding: 15px;
  margin-bottom: 10px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message {
  display: flex;
  margin-bottom: 15px;
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 10px;
}

.message-content {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 8px;
}

.user-message .message-content {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  text-align: right;
}

.ai-message .message-content {
  background-color: #f6ffed;
  border: 1px solid #cfefbc;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.loading-message {
  display: flex;
  align-items: center;
  color: #666;
  font-style: italic;
  gap: 8px;
}

.chat-input {
  padding: 15px;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.input-tip {
  font-size: 12px;
  color: #999;
}
</style>